package com.agrimall.servlet.admin;

import com.agrimall.entity.Order;
import com.agrimall.entity.User;
import com.agrimall.service.OrderService;
import com.agrimall.service.impl.OrderServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 管理员订单管理Servlet
 */
@WebServlet("/admin/order")
public class OrderManageServlet extends HttpServlet {
    private OrderService orderService = new OrderServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User admin = (User) session.getAttribute("admin");
        
        if (admin == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }
        
        String action = request.getParameter("action");
        
        if (action == null || action.equals("") || action.equals("list")) {
            // 订单列表
            listOrders(request, response);
        } else if (action.equals("detail")) {
            // 订单详情
            orderDetail(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User admin = (User) session.getAttribute("admin");
        
        if (admin == null) {
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.print("{\"success\":false,\"message\":\"未登录\"}");
            return;
        }
        
        String action = request.getParameter("action");
        
        if (action != null && action.equals("batchDelete")) {
            // 批量删除订单
            batchDeleteOrders(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    /**
     * 订单列表
     */
    private void listOrders(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String pageStr = request.getParameter("page");
        String orderNo = request.getParameter("orderNo");
        String statusStr = request.getParameter("status");
        String merchantUsername = request.getParameter("merchantUsername");
        String userUsername = request.getParameter("userUsername");
        String receiverName = request.getParameter("receiverName");
        String receiverPhone = request.getParameter("receiverPhone");
        
        int page = 1;
        if (pageStr != null && !pageStr.isEmpty()) {
            try {
                page = Integer.parseInt(pageStr);
            } catch (NumberFormatException e) {
                page = 1;
            }
        }
        int pageSize = 10;
        
        Integer status = null;
        if (statusStr != null && !statusStr.trim().isEmpty()) {
            try {
                status = Integer.parseInt(statusStr.trim());
            } catch (NumberFormatException e) {
                // 忽略
            }
        }
        
        List<Order> orders;
        int totalCount;
        
        // 判断是否有查询条件
        boolean hasConditions = (orderNo != null && !orderNo.trim().isEmpty()) ||
                               status != null ||
                               (merchantUsername != null && !merchantUsername.trim().isEmpty()) ||
                               (userUsername != null && !userUsername.trim().isEmpty()) ||
                               (receiverName != null && !receiverName.trim().isEmpty()) ||
                               (receiverPhone != null && !receiverPhone.trim().isEmpty());
        
        if (hasConditions) {
            orders = orderService.searchOrdersForAdminWithAccount(
                orderNo != null ? orderNo.trim() : null,
                status,
                merchantUsername != null ? merchantUsername.trim() : null,
                userUsername != null ? userUsername.trim() : null,
                receiverName != null ? receiverName.trim() : null,
                receiverPhone != null ? receiverPhone.trim() : null,
                page, pageSize);
            totalCount = orderService.countOrdersForAdminByConditionsWithAccount(
                orderNo != null ? orderNo.trim() : null,
                status,
                merchantUsername != null ? merchantUsername.trim() : null,
                userUsername != null ? userUsername.trim() : null,
                receiverName != null ? receiverName.trim() : null,
                receiverPhone != null ? receiverPhone.trim() : null);
        } else {
            orders = orderService.getOrderListForAdmin(page, pageSize);
            totalCount = orderService.countAllOrders();
        }
        
        // 计算总页数
        int totalPages = totalCount > 0 ? (int) Math.ceil((double) totalCount / pageSize) : 1;
        
        request.setAttribute("orders", orders);
        request.setAttribute("page", page);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("totalPages", totalPages);
        request.setAttribute("orderNo", orderNo);
        request.setAttribute("status", statusStr);
        request.setAttribute("merchantUsername", merchantUsername);
        request.setAttribute("userUsername", userUsername);
        request.setAttribute("receiverName", receiverName);
        request.setAttribute("receiverPhone", receiverPhone);
        
        request.getRequestDispatcher("/admin/order/list.jsp").forward(request, response);
    }
    
    /**
     * 订单详情
     */
    private void orderDetail(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String orderIdStr = request.getParameter("orderId");
        
        if (orderIdStr == null || orderIdStr.trim().isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/admin/order");
            return;
        }
        
        try {
            Long orderId = Long.parseLong(orderIdStr);
            Order order = orderService.getOrderById(orderId);
            
            if (order == null) {
                request.setAttribute("error", "订单不存在");
                request.getRequestDispatcher("/admin/order/list.jsp").forward(request, response);
                return;
            }
            
            request.setAttribute("order", order);
            request.getRequestDispatcher("/admin/order/detail.jsp").forward(request, response);
        } catch (NumberFormatException e) {
            request.setAttribute("error", "订单ID格式错误");
            request.getRequestDispatcher("/admin/order/list.jsp").forward(request, response);
        }
    }
    
    /**
     * 批量删除订单
     */
    private void batchDeleteOrders(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String[] orderIdStrs = request.getParameterValues("orderIds[]");
            
            if (orderIdStrs == null || orderIdStrs.length == 0) {
                out.print("{\"success\":false,\"message\":\"请选择要删除的订单\"}");
                return;
            }
            
            List<Long> orderIds = new java.util.ArrayList<>();
            for (String orderIdStr : orderIdStrs) {
                try {
                    Long orderId = Long.parseLong(orderIdStr.trim());
                    orderIds.add(orderId);
                } catch (NumberFormatException e) {
                    // 忽略无效的ID
                }
            }
            
            if (orderIds.isEmpty()) {
                out.print("{\"success\":false,\"message\":\"没有有效的订单ID\"}");
                return;
            }
            
            int successCount = 0;
            int failCount = 0;
            
            for (Long orderId : orderIds) {
                try {
                    // 删除订单（逻辑删除，将状态设为已取消）
                    Order order = orderService.getOrderById(orderId);
                    if (order != null) {
                        order.setStatus(4); // 已取消
                        boolean success = orderService.updateOrder(order);
                        if (success) {
                            successCount++;
                        } else {
                            failCount++;
                        }
                    } else {
                        failCount++;
                    }
                } catch (Exception e) {
                    failCount++;
                }
            }
            
            if (failCount == 0) {
                out.print("{\"success\":true,\"message\":\"成功删除 " + successCount + " 个订单\"}");
            } else {
                out.print("{\"success\":true,\"message\":\"成功删除 " + successCount + " 个订单，失败 " + failCount + " 个\"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\":false,\"message\":\"服务器错误：" + e.getMessage() + "\"}");
        } finally {
            out.flush();
            out.close();
        }
    }
}

